package org.cn.osiris.basic.util;

import org.cn.osiris.basic.jwt.JwtUtils;
import org.cn.osiris.basic.jwt.LoginData;
import org.cn.osiris.basic.jwt.Payload;
import org.cn.osiris.basic.jwt.RsaUtils;
import org.cn.osiris.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

public class LoginContext {

    public static Logininfo getLogininfo(HttpServletRequest request){
    try {
        //1.从请求头获取token：因为每次发送axios请求之前都会在axios的前置拦截器携带token到请求头
        String jwtToken = request.getHeader("token");
        if(jwtToken != null){
            //2.获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
            //3.解密
            Payload<LoginData> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, LoginData.class);
            //解密之后获取载荷数据
            Logininfo logininfo = payload.getLoginData().getLogininfo();
            return logininfo;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
}